﻿using System;
using System.IO.Ports;
using System.Text;
using DataMonitor.Logging;
namespace DataMonitor.Model
{
    public class SerialportMonitor : MonitorBase
    {
        private SerialPort _serialPort = new SerialPort();
        public SerialportMonitor(string name, int port)
        {
            _serialPort.PortName = name;
            _serialPort.BaudRate = port;
            _serialPort.Parity = Parity.None;
            _serialPort.StopBits = StopBits.One;
            _serialPort.DataBits = 8;
            _serialPort.DataReceived += _serialPort_DataReceived;
            try
            {
                _serialPort.Open();
            }
            catch (Exception e)
            {
                Log4NetAdapter.Instance.Write(e);
            }
        }

        ~SerialportMonitor()
        {
            try
            {
                if (_serialPort.IsOpen)
                {
                    _serialPort.Close();
                }
            }
            catch (Exception e)
            {
                Log4NetAdapter.Instance.Write(e);
            }
        }

        void _serialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            string msg = _serialPort.ReadExisting();
            var relmsg = OnReceiveEvent(Encoding.Default.GetBytes(msg));
            if (!string.IsNullOrEmpty(relmsg) && ShowMsgAction != null)
            {
                ShowMsgAction(relmsg);
            }
        }
        public override bool Send(byte[] buffer)
        {
            try
            {
                if (_serialPort.IsOpen)
                {
                    _serialPort.Write(buffer, 0, buffer.Length);
                    return true;
                }
            }
            catch (Exception e)
            {
                Log4NetAdapter.Instance.Write(e);
            }
            return false;
        }
    }
}
